package endpoint

import (
	"mcode/apps/admin/internal/entity"
	"mcode/apps/admin/internal/usecase"
	"mcode/pkg/ctx"
	"mcode/pkg/query"
	"mcode/pkg/response"
	"mcode/pkg/validator"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ApiHandler struct {
	apiUseCase usecase.ApiUseCase
	validator  *validator.Validator
}

func NewApiHandler(apiUseCase usecase.ApiUseCase, validator *validator.Validator) *ApiHandler {
	return &ApiHandler{
		apiUseCase: apiUseCase,
		validator:  validator,
	}
}

func (h *ApiHandler) GetApi(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的ID")
		return
	}

	api, err := h.apiUseCase.GetApi(c.Request.Context(), uint(id))
	if err != nil {
		response.Error(c, http.StatusNotFound, "记录不存在")
		return
	}

	response.Success(c, api)
}

func (h *ApiHandler) UpdateApi(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的ID")
		return
	}

	api := new(entity.Api)
	if err := c.ShouldBindJSON(api); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(api); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	api.Id = uint(id)
	if err := h.apiUseCase.UpdateApi(c.Request.Context(), api); err != nil {
		response.Error(c, http.StatusInternalServerError, "更新失败")
		return
	}

	response.Success(c, api)
}

func (h *ApiHandler) DeleteApi(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		response.Error(c, http.StatusBadRequest, "无效的ID")
		return
	}

	if err := h.apiUseCase.DeleteApi(c.Request.Context(), uint(id)); err != nil {
		response.Error(c, http.StatusInternalServerError, "删除失败")
		return
	}

	response.Success(c, nil)
}

func (h *ApiHandler) CreateApi(c *gin.Context) {
	api := new(entity.Api)
	if err := c.ShouldBindJSON(api); err != nil {
		response.Error(c, http.StatusBadRequest, "无效的请求数据")
		return
	}

	if err := h.validator.ValidateStruct(api); err != nil {
		errors := h.validator.TranslateError(err)
		response.ValidationError(c, errors)
		return
	}

	if err := h.apiUseCase.CreateApi(c.Request.Context(), api); err != nil {
		response.Error(c, http.StatusInternalServerError, "创建失败")
		return
	}

	response.Success(c, api)
}

func (h *ApiHandler) ListApis(c *gin.Context) {
	params := query.NewQuery().
		AddCondition("status", query.OpEq, 1).
		AddOrderBy("id DESC").
		SetPagination(ctx.GetPagination(c)).
		Select("id", "username", "email", "role", "status", "created_at", "updated_at")
	result, err := h.apiUseCase.List(c.Request.Context(), params)
	if err != nil {
		response.ServerError(c, err)
		return
	}

	response.Success(c, result)
}
